package com.androidcourse.shounews.Fragment;

import static android.content.ContentValues.TAG;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.androidcourse.shounews.Entity.MyNews;
import com.androidcourse.shounews.HttpUtil.MyOkHttp;
import com.androidcourse.shounews.HttpUtil.NewsHttp;
import com.androidcourse.shounews.MyDialog.MyDialog;
import com.androidcourse.shounews.R;
import com.androidcourse.shounews.SqlLite.MyDBHelper;
import com.androidcourse.shounews.Toast.MyCustomToast;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AddNewsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AddNewsFragment extends Fragment implements View.OnClickListener {
    private MyDBHelper myDBHelper;
    private EditText wechat;
    private EditText myNews_link;
    private EditText myNews_name;
    private Button addWechat;
    private Button addMyNews;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_add_wechat_news, container, false);
    }
    //创建myDBHelper实例
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myDBHelper=MyDBHelper.getInstance(getContext());
        myDBHelper.getRead();
        myDBHelper.getWrite();
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        wechat=getActivity().findViewById(R.id.wechat_link);
        myNews_link=getActivity().findViewById(R.id.my_news_link);
        myNews_name=getActivity().findViewById(R.id.my_news_name);
        getActivity().findViewById(R.id.add_my_news_button).setOnClickListener(this);
        getActivity().findViewById(R.id.add_wechat_button).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        if(id==R.id.add_my_news_button){
            String name=myNews_name.getText().toString().trim();
            String link=myNews_link.getText().toString().trim();
            if(!isValidUrl(link)) {
                dialog("您输入的链接有误");
                return;
            }
            if(myDBHelper.queryByName(name).size()!=0){
                dialog("您输入的标签重复");
                return;
            }
            myDBHelper.insert(new MyNews(name,link));
            new MyCustomToast(getContext(),MyCustomToast.SUCCESS,"添加成功");
        }else
            if(id==R.id.add_wechat_button){
            String link=wechat.getText().toString().trim();
            if(!isValidUrl(link)) {
                dialog("您输入的链接有误!");
                return;
            }
            if(!isWechatArticle(link)){
                dialog("您输入的链接不是公众号文章!");
                return;
            }
            NewsHttp.addWechatNews(link)
                    .thenAccept(res->{
               getActivity().runOnUiThread(
                       new Runnable() {
                           @Override
                           public void run() {
                               if(res.getCode()==1)
                               {
                                   new MyCustomToast(getContext(),MyCustomToast.SUCCESS,"添加成功");
                               }
                               else
                                   dialog(res.getMessage());
                           }
                       });
            })
                    .exceptionally(e->{
                        Log.e(TAG, "onClick: ", e);
                        getActivity().runOnUiThread(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                           dialog("服务端异常");
                                    }
                                });
                        return null;
                    });
            }

    }

    /**
     * 判断url是否合法
     * @param url 链接
     * @return
     */
    private boolean isValidUrl(String url){
        try {
            new URL(url);
            return true;
        } catch (MalformedURLException e) {
            return false;
        }
    }

    /**
     * 判断是否为微信公众号文章
     * @param url
     * @return
     */
    public static boolean isWechatArticle(String url) {
        return url.startsWith("https://mp.weixin.qq.com/s/");
    }
    /**
     * @param message 弹框
     */
    private void dialog(String message){
        MyDialog myDialog=new MyDialog(getContext());
        myDialog.setsMessage(message).setsConfirm("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog.dismiss();
                    }
                }).show();
    }
}